﻿#region License
/***********************************************
 *  WCFReactiveX v.1
 *  Written by James Levingston
 *  
 *  To get latest version or to see latest info:
 *  http://wcfreactivex.codeplex.com/
 *  
 *  The MIT License (MIT)
 *  http://en.wikipedia.org/wiki/MIT_License
 *  Copyright (C) <2011> by <James Levingston>
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 ***/
#endregion

using System;

namespace WCFReactiveX
{
    public class RxController
    {
        protected virtual object Provider { get; set; }
        protected virtual object Reporter { get; set; }

        public  virtual IFactory Factory { get; private set; }

        public RxController() { Factory = new Factory(); }
        public RxController(IFactory factory) { Factory = factory; }

        public event Action<IProviderTransaction> OnProviderRequest;
        public event Action<IProviderTransaction> OnProviderResponse;

        protected virtual void ValidateContext<TContext>(TContext context, Action<TContext> validate)
        {
            if (context == null)
                throw new ProviderException("Error: " + typeof(TContext).Name + " is null.");
            if (validate == null)
                return;
            validate(context);
        }
        protected virtual void Provider_OnResponse(IProviderTransaction obj)
        {
            if (this.OnProviderResponse != null)
                this.OnProviderResponse(obj);            
        }
        protected virtual void Provider_OnRequest(IProviderTransaction obj)
        {
            if (this.OnProviderRequest != null)
                this.OnProviderRequest(obj);
        }
        public virtual IProviderResult<TResult, TMessage> Result<TResult, TContext, TToken, TMessage>()
        {
            if (this.Reporter == null)
                return null;
            return ((Reporter<TContext, TToken, TResult, TMessage>)this.Reporter).Result;
        }
        public virtual IProviderResult<TMessage> Result<TContext, TToken, TMessage>() where TContext : ProviderContext<TToken>
        {
            if (this.Reporter == null)
                return null;
            return ((Reporter<TContext, TToken, TMessage>)this.Reporter).Result;
        }
        protected virtual IProvider<TContext, TToken, TMessage, TException, TClient> GetProvider<TResult, TContext, TToken, TMessage, TException, TClient>()
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            return GetProvider<TResult, TContext, TToken, TMessage, TException, TClient>(null);
        }
        protected virtual Reporter<TContext, TToken, TMessage> GetReporter<TContext, TToken, TMessage>()
        {
            return new Reporter<TContext, TToken, TMessage>();
        }
        protected virtual Reporter<TContext, TToken, TResult, TMessage> GetReporter<TResult, TContext, TToken, TMessage>()
        {
            return new Reporter<TContext, TToken, TResult, TMessage>();
        }
        protected virtual IProvider<TContext, TToken, TMessage, TException, TClient> GetProvider<TResult, TContext, TToken, TMessage, TException, TClient>(Action<IProviderResult<TMessage>> resultAction)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            var c = new Provider<TContext, TToken, TMessage, TException, TClient>(this.Factory);
            var r = (Reporter<TContext, TToken, TResult, TMessage>)this.GetReporter<TResult, TContext, TToken, TMessage>();

            if (resultAction != null)
                r.OnResult += resultAction;
            else
                r.OnResult += new Action<IProviderResult<TResult, TMessage>>(reporter_OnResult<TResult, TMessage>);
            
            this.SetupProvider<TContext, TToken, TMessage, TException, TClient>(c,r);
            return c;
        }
        protected virtual void reporter_OnResult<TResult, TMessage>(IProviderResult<TResult, TMessage> obj)
        {
            //Do nothing, just a stub
        }       
        private void DestroyProvider<TResult, TContext, TToken, TMessage, TException, TClient>()
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            BreakDownProvider<TContext, TToken, TMessage, TException, TClient>((IReporter<TMessage>)this.Reporter);
        }        
        protected virtual IProvider<TContext, TToken, TMessage, TException, TClient> GetProvider<TContext, TToken, TMessage, TException, TClient>()
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            return new Provider<TContext, TToken, TMessage, TException, TClient>(this.Factory);
        }
        protected virtual IProvider<TContext, TToken, TMessage, TException, TClient> GetProvider<TContext, TToken, TMessage, TException, TClient>(Action<IProviderResult<TMessage>> resultAction)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            var c = this.GetProvider<TContext, TToken, TMessage, TException, TClient>();
            var r = (Reporter<TContext, TToken, TMessage>)this.GetReporter<TContext, TToken, TMessage>();

            if(resultAction != null)
                r.OnResult += resultAction;
            else
                r.OnResult += new Action<IProviderResult<TMessage>>(reporter_OnResult<TMessage>);

            this.SetupProvider<TContext, TToken, TMessage, TException, TClient>(c, r);
            return c;
        }        
        protected virtual void reporter_OnResult<TMessage>(IProviderResult<TMessage> obj)
        {
            //Do nothing, just a stub
        }
        private void DestroyProvider<TContext, TToken, TMessage, TException, TClient>()
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            BreakDownProvider<TContext, TToken, TMessage, TException, TClient>((IReporter<TMessage>)this.Reporter);
        }
        protected virtual void SetupProvider<TContext, TToken, TMessage, TException, TClient>(
            IProvider<TContext, TToken, TMessage, TException, TClient> Provider,
            IReporter<TMessage> reporter)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            reporter.OnRequest += new Action<IProviderTransaction>(Provider_OnRequest);
            reporter.OnResponse += new Action<IProviderTransaction>(Provider_OnResponse);
            Provider.Subscribe(reporter);
            //Set the local variables
            this.Reporter = reporter;
            this.Provider = Provider;
        }
        private void BreakDownProvider<TContext, TToken, TMessage, TException, TClient>(IReporter<TMessage> reporter)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            var c = (Provider<TContext, TToken, TMessage, TException, TClient>)Provider;
            reporter.Unsubscribe();
            c.EndRequest();
        }
        
        public virtual IProviderResult<TResult, TMessage> ExecuteRequest<TContext, TResult, TToken, TMessage, TException, TClient>(
            TContext context,
            Func<TContext, IProviderResult<TResult, TMessage>> request,
            Action<TContext> validation,
            System.ServiceModel.ClientBase<TClient> client)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            try
            {
                var provider = this.GetProvider<TResult, TContext, TToken, TMessage, TException, TClient>();
                provider.ExecuteServiceRequest<TResult>(
                            context,
                            (TContext t) =>
                            {
                                this.ValidateContext<TContext>(context, validation);
                                return request(context);
                            },
                            client);
            }
            finally
            {
                this.DestroyProvider<TResult, TContext, TToken, TMessage, TException, TClient>();
            }
            return (IProviderResult<TResult, TMessage>)this.Result<TResult, TContext, TToken, TMessage>();
        }
        
        public virtual IProviderResult<TMessage> ExecuteRequest<TContext, TToken, TMessage, TException, TClient>(
           TContext context,
           Func<TContext, IProviderResult<TMessage>> request,
           Action<TContext> validation,
           System.ServiceModel.ClientBase<TClient> client)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            try
            {
                var provider = this.GetProvider<TContext, TToken, TMessage, TException, TClient>();
                provider.ExecuteServiceRequest(
                            context,
                            (TContext t) =>
                            {
                                this.ValidateContext<TContext>(context, validation);
                                return request(context);
                            },
                            client);
            }
            finally
            {
                this.DestroyProvider<TContext, TToken, TMessage, TException, TClient>();
            }
            return (IProviderResult<TMessage>)this.Result<TContext, TToken, TMessage>();
        }

        public void ExecuteRequestAsync<TContext, TResult, TToken, TMessage, TException, TClient>(
           TContext context,
           Action<TContext> contextValidation,
           Func<TContext, IProviderResult<TResult,TMessage>> clientRequest,
           Action<IProviderResult<TMessage>> resultEvent,
           System.ServiceModel.ClientBase<TClient> client)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            try
            {
                var provider = this.GetProvider<TResult, TContext, TToken, TMessage, TException, TClient>(resultEvent);
                provider.ExecuteServiceRequest<TResult>(
                            context,
                            (TContext t) =>
                            {
                                this.ValidateContext<TContext>(context, contextValidation);
                                return clientRequest(context);
                            },
                            client);
            }
            finally
            {
                this.DestroyProvider<TResult, TContext, TToken, TMessage, TException, TClient>();
            }
        }

        public virtual void ExecuteRequestAsync<TContext, TToken, TMessage, TException, TClient>(
           TContext context,
           Action<TContext> contextValidation,
           Func<TContext, IProviderResult<TMessage>> clientRequest,
           Action<IProviderResult<TMessage>> resultEvent,
           System.ServiceModel.ClientBase<TClient> client)
            where TContext : ProviderContext<TToken>
            where TClient : class
            where TException : ProviderException
        {
            try
            {
                var provider = this.GetProvider<TContext, TToken, TMessage, TException, TClient>(resultEvent);
                provider.ExecuteServiceRequest(
                            context,
                            (TContext t) =>
                            {
                                this.ValidateContext<TContext>(context, contextValidation);
                                return clientRequest(context);
                            },
                            client);
            }
            finally
            {
                this.DestroyProvider<TContext, TToken, TMessage, TException, TClient>();
            }
        }
    }
}
